//
//  PayMoneyVC.m
//  zhiche--delivery
//
//  Created by 王亚陆 on 16/6/3.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "PayMoneyVC.h"
#import "Common.h"
#import <Masonry.h>
#import "RootViewController.h"
#import "AcceptCarCell.h"
@interface PayMoneyVC ()
{
    UIView * nav;
    UITableView * table;
    NSMutableArray * dataSouceArr;
    NSMutableArray * imageBtnArr;
    ZBarReaderView * readview;
    RootViewController * TabBar;
    NSMutableDictionary * DataSouceDic;

}

@property(nonatomic,strong) UIImageView *scanZomeBack;
@end


@implementation PayMoneyVC

- (void)viewDidLoad {
    [super viewDidLoad];
    TabBar = [RootViewController defaultsTabBar];
    nav = [self createNav:@"我要接车"];
    dataSouceArr = [[NSMutableArray alloc]init];
    DataSouceDic = [[NSMutableDictionary alloc]init];
    imageBtnArr = [[NSMutableArray alloc]init];
    
    [self.view addSubview:nav];
    [self createUI];
}

#pragma mark 初始化扫描
- (void)InitScan
{

}
-(void)createUI{
    UIButton * btnLabel = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnLabel setTitle:@"收车扫一扫" forState:UIControlStateNormal];
    [btnLabel setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    btnLabel.titleLabel.font = Font(FontOfSize14);
    btnLabel.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [btnLabel addTarget:self action:@selector(pressBtnLabel) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnLabel];
    [btnLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).with.offset(14*kWidth);
        make.top.mas_equalTo(nav.mas_bottom).with.offset(1);
        make.size.mas_equalTo(CGSizeMake((Main_Width-28)*kWidth, 33*kHeight));
    }];
    
    UIImageView * RightImage= [[UIImageView alloc]init];
    RightImage.image = [UIImage imageNamed:@"common_list_arrows_more"];
    [self.view addSubview:RightImage];
    [RightImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).with.offset(-15*kWidth);
        make.centerY.mas_equalTo(btnLabel.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(8*kWidth, 13*kHeight));
    }];
    
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 65*kHeight, Main_Width,Main_height-65*kHeight) style:UITableViewStylePlain];
    [table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    table.delegate = self;
    table.dataSource = self;
    
    [table reloadData];
    [self.view addSubview:table];
    [table mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(btnLabel.mas_bottom).with.offset(0*kHeight);
        make.size.mas_equalTo(CGSizeMake(Main_Width, 130*3*kHeight));
        
    }];
    UIButton * ConfirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [ConfirmBtn addTarget:self action:@selector(pressConfirm) forControlEvents:UIControlEventTouchUpInside];
    [ConfirmBtn setTitle:@"确认接车" forState:UIControlStateNormal];
    [ConfirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    ConfirmBtn.backgroundColor = [UIColor greenColor];
    ConfirmBtn.layer.borderWidth = 0.8;
    ConfirmBtn.layer.cornerRadius = 5;
    [self.view addSubview:ConfirmBtn];
    [ConfirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(table.mas_bottom).with.offset(10*kHeight);
        make.size.mas_equalTo(CGSizeMake(Main_Width*0.75, 33*kHeight));
    }];
    UIButton * ConcelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [ConcelBtn addTarget:self action:@selector(pressConcel) forControlEvents:UIControlEventTouchUpInside];
    [ConcelBtn setTitle:@"拒绝接车" forState:UIControlStateNormal];
    [ConcelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    ConcelBtn.backgroundColor = [UIColor greenColor];
    ConcelBtn.layer.borderWidth = 0.8;
    ConcelBtn.layer.cornerRadius = 5;
    [self.view addSubview:ConcelBtn];
    [ConcelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(ConfirmBtn.mas_bottom).with.offset(10*kHeight);
        make.size.mas_equalTo(CGSizeMake(Main_Width*0.75, 33*kHeight));
    }];
}
#pragma mark 初始化扫描

-(void)pressBtnLabel{
    
    [self scanBtnAction];
}
-(void)scanBtnAction
{
    num = 0;
    upOrdown = NO;
    //初始话ZBar
    ZBarReaderViewController * reader = [ZBarReaderViewController new];
    //设置代理
    reader.readerDelegate = self;
    //支持界面旋转
    reader.supportedOrientationsMask = ZBarOrientationMaskAll;
    reader.showsHelpOnFail = NO;
    reader.scanCrop = CGRectMake(0.1, 0.2, 0.8, 0.8);//扫描的感应框
    ZBarImageScanner * scanner = reader.scanner;
    [scanner setSymbology:ZBAR_I25
                   config:ZBAR_CFG_ENABLE
                       to:0];
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 420)];
    view.backgroundColor = [UIColor clearColor];
    reader.cameraOverlayView = view;
    
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 280, 40)];
    label.text = @"请将扫描的二维码至于下面的框内\n谢谢！";
    label.textColor = [UIColor whiteColor];
    label.textAlignment = 1;
    label.lineBreakMode = 0;
    label.numberOfLines = 2;
    label.backgroundColor = [UIColor clearColor];
    [view addSubview:label];
    
    UIImageView * image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pick_bg.png"]];
    image.frame = CGRectMake(20, 80, 280, 280);
    [view addSubview:image];
    
    _line = [[UIImageView alloc] initWithFrame:CGRectMake(30, 10, 220, 2)];
    _line.image = [UIImage imageNamed:@"line.png"];
    [image addSubview:_line];
    //定时器，设定时间过1.5秒，
    timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
    
    [self presentViewController:reader animated:YES completion:^{
        
    }];
}
-(void)animation1
{
    if (upOrdown == NO) {
        num ++;
        _line.frame = CGRectMake(30, 10+2*num, 220, 2);
        if (2*num == 260) {
            upOrdown = YES;
        }
    }
    else {
        num --;
        _line.frame = CGRectMake(30, 10+2*num, 220, 2);
        if (num == 0) {
            upOrdown = NO;
        }
    }
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [timer invalidate];
    _line.frame = CGRectMake(30, 10, 220, 2);
    num = 0;
    upOrdown = NO;
    [picker dismissViewControllerAnimated:YES completion:^{
        [picker removeFromParentViewController];
    }];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [timer invalidate];
    _line.frame = CGRectMake(30, 10, 220, 2);
    num = 0;
    upOrdown = NO;
    [picker dismissViewControllerAnimated:YES completion:^{
        [picker removeFromParentViewController];
        UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
        //初始化
        ZBarReaderController * read = [ZBarReaderController new];
        //设置代理
        read.readerDelegate = self;
        CGImageRef cgImageRef = image.CGImage;
        ZBarSymbol * symbol = nil;
        id <NSFastEnumeration> results = [read scanImage:cgImageRef];
        for (symbol in results)
        {
            break;
        }
        NSString * result;
        if ([symbol.data canBeConvertedToEncoding:NSShiftJISStringEncoding])
            
        {
            result = [NSString stringWithCString:[symbol.data cStringUsingEncoding: NSShiftJISStringEncoding] encoding:NSUTF8StringEncoding];
        }
        else
        {
            result = symbol.data;
            
        }

        [self createUIAlertController:@"扫码成功"];

        NSLog(@"%@",result);
        
    }];
}

-(void)pressConcel{
    
    
}

-(void)pressConfirm{
    
    [Common requestWithUrlString:Order_receipt contentType:@"application/json" finished:^(id responseObj){

        DataSouceDic = responseObj[@"data"];
        dataSouceArr = DataSouceDic[@"orders"];
        for (int i=0; i<dataSouceArr.count; i++) {
            NSString * string = [NSString stringWithFormat:@"0"];
            [imageBtnArr addObject:string];
        }
        [table reloadData];
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
}

-(void)viewWillAppear:(BOOL)animated{
    
    [TabBar setTabBarHidden:YES];
    [Common requestWithUrlString:Order_receipt contentType:@"application/json" finished:^(id responseObj){
        
        DataSouceDic = responseObj[@"data"];
        dataSouceArr = DataSouceDic[@"orders"];
        for (int i=0; i<dataSouceArr.count; i++) {
            NSString * string = [NSString stringWithFormat:@"0"];
            [imageBtnArr addObject:string];
        }
        [table reloadData];
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *str=@"str";
    AcceptCarCell * cell =  [tableView dequeueReusableCellWithIdentifier:str];
    if (cell ==nil) {
        cell = [[AcceptCarCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if ([imageBtnArr[indexPath.row]isEqualToString:@"0"]) {
        cell.imageBtn.backgroundColor = [UIColor whiteColor];
        cell.imageBtn.selected = NO;
    }else{
        cell.imageBtn.backgroundColor = [UIColor blueColor];
        cell.imageBtn.selected = YES;
    }
    [cell showInfo:dataSouceArr[indexPath.row]];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    for (int i =0; i<imageBtnArr.count; i++) {
        [imageBtnArr replaceObjectAtIndex:i withObject:@"0"];
    }
    AcceptCarCell *cell = [table cellForRowAtIndexPath:indexPath];
    if (cell.imageBtn.selected) {
        cell.imageBtn.backgroundColor = [UIColor whiteColor];
        cell.imageBtn.selected = NO;
    }else{
        cell.imageBtn.backgroundColor = [UIColor blueColor];
        cell.imageBtn.selected = YES;
        [imageBtnArr replaceObjectAtIndex:indexPath.row withObject:@"1"];
    }
    [table reloadData];

}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 130*kHeight;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return dataSouceArr.count;
//    return 3;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)createUIAlertController:(NSString*)title

{
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action1];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}


@end
